import {
  smartDictionariesBulkDeletes,
  smartDictionariesConvertChinese,
  smartDictionariesCreate,
  smartDictionariesIsFavorited,
  smartDictionariesPagination,
} from '@/services/swagger/smartDictionaries';
import { HeartFilled, HeartOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, message, Select, Switch } from 'antd';
import React, { useRef, useState } from 'react';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.ChineseDictionaryCreateInputModel) => {
  const hide = message.loading('正在添加');
  try {
    await smartDictionariesCreate({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败, 请再次重试!');
    return false;
  }
};

/**
 * @en-US Toggle favorite
 * @zh-CN 是否收藏
 * @param fields
 */
const handleToggleFavorite = async (fields: API.ChineseDictionaryOutputModel) => {
  const hide = message.loading('正在修改');
  try {
    await smartDictionariesIsFavorited({ id: fields.id as number });
    hide();
    if (fields.isFavorited) {
      message.success('取消收藏');
    } else {
      message.success('收藏成功');
    }
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请再次重试!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.ChineseDictionaryOutputModel[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const ids = {
      ids: selectedRows.map((row) => row.id).join(','), // 示例 ID 列表
    } as API.SmartDictionariesBulkDeletesParams;

    await smartDictionariesBulkDeletes(ids);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败, 请再次重试！');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.ChineseDictionaryOutputModel>();
  const [selectedRowsState, setSelectedRows] = useState<API.ChineseDictionaryOutputModel[]>([]);

  const [isTraditional, setIsTraditional] = useState(false);

  const convertToTraditional = async (
    row: API.ChineseDictionaryOutputModel,
    isToSimplified: boolean,
  ) => {
    const data = await smartDictionariesConvertChinese({
      word: row.word,
      description: row.description,
      isToSimplified: isToSimplified,
    });
    row.word = data.data?.word;
    row.description = data.data?.description;
    return row; // 示例为直接返回
  };

  const handleToggleLanguage = async (toTraditional: boolean) => {
    if (currentRow) {
      const convertedRow = await convertToTraditional(currentRow, !toTraditional);
      setCurrentRow(convertedRow); // 更新当前行数据
    }
    setIsTraditional(toTraditional);
  };
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.ChineseDictionaryOutputModel>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.updateForm.chineseWord.wordLabel"
          defaultMessage="Word"
        />
      ),
      dataIndex: 'word',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.updateForm.isFavorited.favoritedLabel"
          defaultMessage="Is favorited"
        />
      ),
      dataIndex: 'isFavorited',
      valueType: 'select',
      valueEnum: {
        true: { text: '收藏' },
        false: { text: '未收藏' },
      },
      render: (text, entity) => {
        return (
          <a
            onClick={() => {
              handleToggleFavorite(entity);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
          >
            {entity.isFavorited ? <HeartFilled style={{ color: 'red' }} /> : <HeartOutlined />}
          </a>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Select {...rest} placeholder="请选择"></Select>;
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.created" defaultMessage="Created time" />,
      sorter: true,
      dataIndex: 'created',
      valueType: 'dateTime',
      search: false,
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.ChineseDictionaryOutputModel, API.SmartDictionariesPaginationParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.chinese.word.list',
          defaultMessage: 'Word list',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={smartDictionariesPagination}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.searchTable.createForm.newChineseWord',
          defaultMessage: 'New word',
        })}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.VocabularyCreateInputModel);
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.chinese.word"
                  defaultMessage="Word is required"
                />
              ),
            },
          ]}
          width="md"
          name="word"
        />
      </ModalForm>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.word && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h2 style={{ margin: 0 }}>{currentRow.word}</h2>
              <Switch
                checked={isTraditional}
                onChange={handleToggleLanguage}
                checkedChildren="简体"
                unCheckedChildren="繁体"
                style={{ marginLeft: '20px' }}
              />
            </div>
            {currentRow.description ? (
              <>
                {(() => {
                  try {
                    const descriptionObj = JSON.parse(
                      currentRow.description.replaceAll('`', '').replaceAll('~', ''),
                    );
                    return (
                      <div>
                        {descriptionObj?.h?.map((result: any, index: number) => (
                          <div key={index} style={{ marginBottom: '50px' }}>
                            <div style={{ marginBottom: '20px' }}>
                              读音{index + 1}：【 {result?.p}】
                            </div>
                            {result?.d.map((result2: any, index2: number) => (
                              <div key={index2} style={{ marginBottom: '30px' }}>
                                <p>
                                  {index2 + 1}：{result2?.f}
                                  {result2?.type ? `【${result2.type}词】` : ''}
                                </p>
                                <div>
                                  {Array.isArray(result2.e) && result2.e.length > 0
                                    ? result2.e.map((example: string, idx: number) => (
                                        <div key={idx} style={{ marginBottom: '10px' }}>
                                          {example}
                                        </div>
                                      ))
                                    : ''}
                                </div>
                                <div>
                                  {Array.isArray(result2.q) && result2.q.length > 0
                                    ? result2.q.map((example: string, idx: number) => (
                                        <div key={idx} style={{ marginBottom: '10px' }}>
                                          {example}
                                        </div>
                                      ))
                                    : ''}
                                </div>
                              </div>
                            ))}
                          </div>
                        ))}
                      </div>
                    );
                  } catch (error) {
                    return <p>Error parsing description.</p>;
                  }
                })()}
              </>
            ) : (
              <p>No description available.</p>
            )}
          </div>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
